package com.nine.mq.customer;

import com.nine.mq.config.constanst.MqConstanst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 如果当前队列不存在，则会抛出异常：
 * org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$DeclarationException: Failed to declare queue(s):[test_queue1]
 * <p>
 * 解决办法：
 * 可以看DirectConsumer
 */
@Slf4j
@Component
@RabbitListener(queues = MqConstanst.QUEUE_NAME)
public class DirectConsumer02 {

    @RabbitHandler
    public void receive(Map<String, String> map, Channel channel, Message message) {

        // map值和message的值是一样的，但是表现形式不一样
        log.info("DirectConsumer02 接收到消息[map]: {}", map.toString());
        try {
            String msg = new String(message.getBody(), "UTF-8");
            log.info("DirectConsumer02 接收到消息[message]: {}", msg);

            // 手动确认消息已被消费
            // 由于设置了手动确认，所以需要手动发送ack，注意：如果设置了自动应答，这里又进行手动应答，会出现double ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
